const app = getApp();
const db = wx.cloud.database();
const _ = db.command;
const $ = _.aggregate;
var that;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    article: {
      type: '',
      title: '',
      author: '',
      authorAvatar: '',
      date: '',
      content: '', // 暂时用字符串
      teamName: '',
      postId: ''
    },
    replyTo: {
      id: '',
      name: '',
      openid: ''
    },
    commentText: '',
    commentList: [],
    cmtDisabled: true,
    typeMap: app.globalData.typeMap
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    that = this;
    console.log(options);
    this.setData({
      postId: options.id
    });
    this.initArticle(options.id);
    this.getComment();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  /**
   * 初始化页面（不包括评论）
   * @param {String} postId 帖子ID
   */
  initArticle: async function (postId) {
    // 获取队伍信息，其中相关用户的信息只有openid
    var teamInfo = await db.collection('post').doc(postId).get();
    console.log('team:', teamInfo);
    this.setData({
      article: teamInfo.data,
    });
    // 获取帖子作者信息
    var leaderInfo = await db.collection('user').where({
      _openid: teamInfo.data._openid
    }).get();
    console.log('leader:', leaderInfo);
    this.setData({
      'article.author': leaderInfo.data[0].nickName,
      'article.authorAvatar': leaderInfo.data[0].avatarUrl
    });
    // 获取成员信息
    var membersInfo = await db.collection('user').where({
      _openid: _.in(teamInfo.data.members)
    }).get();
    console.log('memebrs info', membersInfo);
    this.setData({
      'article.members': membersInfo.data
    });
  },

  /**
   * 评论input输入时触发，当评论内容不为空时设置可以提交
   * @param {*} arg input组件input事件参数
   */
  setCmtAble: function (arg) {
    console.log('on input comment', arg);
    this.setData({
      cmtDisabled: arg.detail.value == '' ? true : false
    });
  },

  /**
   * 提交评论
   * @param {*} arg 表单参数
   */
  submitComment: function (arg) {
    // 先禁用发布按钮
    this.setData({
      cmtDisabled: true
    });
    var timeStr = this.getCurTime();
    var commentText = arg.detail.value.commentText;
    console.log('submit comment', arg);
    var article = this.data.article;
    db.collection('comment').add({
      data: {
        postId: article._id,
        content: commentText,
        time: timeStr,
        replyTo: this.data.replyTo.openid == '' ? null : this.data.replyTo.openid,
        masterId: this.data.replyTo.id == '' ? null : this.data.replyTo.id
      }
    }).then((res) => {
      wx.showToast({
        title: '评论成功'
      });
      console.log('comment submit done', res);
      // 更新这条新记录的masterId（没有回复任何人时才更新）
      // masterId这个设计虽然能够方便聚合，但这里也是一个不便之处
      // 可能还要考虑添加评论和更新masterId的原子性
      if (that.data.replyTo.id == '') {
        var _id = res._id;
        db.collection('comment').doc(_id).update({
          data: {
            masterId: _id
          }
        });
      }
      // 清空输入框内容以及回复状态
      that.setData({
        commentText: '',
        replyTo: {
          id: '',
          name: '',
          openid: ''
        },
        cmtDisabled: true
      });
      // 刷新评论列表
      that.getComment();
    }).catch((res) => {
      console.log('comment failed', res);
      that.setData({
        cmtDisabled: false
      });
    });
  },

  /**
   * 获取当前文章的评论列表
   */
  getComment: function () {
    wx.cloud.callFunction({
      name: 'getArticleComment',
      data: {
        postId: this.data.postId,
        skip: 0,
        limit: 0
      }
    }).then((res) => {
      console.log('comment list', res);
      that.setData({
        commentList: res.result.data
      });
    }).catch((res) => {
      console.log('get comment failed', res);
    });
  },

  /**
   * 设置回复的评论id
   * @param {*} arg tap事件参数
   */
  setReplyTo: function (arg) {
    console.log('set reply to', arg);
    var id = arg.currentTarget.dataset.id;
    var name = arg.currentTarget.dataset.name;
    var openid = arg.currentTarget.dataset.openid;
    this.setData({
      replyTo: {
        id: id == this.data.replyTo.id ? '' : id,
        name: name == this.data.replyTo.name ? '' : name,
        openid: openid == this.data.replyTo.openid ? '' : openid
      }
    });
  },

  /**
   * @brief 申请加入队伍
   */
  applyTeam: function () {
    wx.showModal({
      title: '提示',
      content: '确定申请加入这个队伍吗？'
    }).then((res) => {
      if (res.confirm) {
        wx.cloud.callFunction({
          name: 'applyForTeam',
          data: {
            teamId: this.data.postId
          }
        }).then((res) => {
          console.log(res);
          var errCode = res.result.errCode;
          var toastText;
          switch (errCode) {
            case 0:
              toastText = '申请成功';
              break;
            case 1:
              toastText = '队伍ID无效';
              break;
            case 2:
              toastText = '已经在队伍中';
              break;
            case 3:
              toastText = '已经申请过';
              break;
            case 4:
              toastText = '您还没有注册';
              break;
            default:
              toastText = '未知错误';
              break;
          }
          wx.showToast({
            icon: errCode == 0 ? 'success' : 'error',
            title: toastText,
            duration: 1500
          });
        }).catch((res) => {
          console.log(res);
        });
      }
    })
  },

  /**
   * 获取时间字符串，格式为yyyy-mm-dd-hh-mm-ss
   */
  getCurTime: function () {
    var d = new Date();
    var time = String(d.getFullYear()) + '-' +
      String(d.getMonth() + 1) + '-' +
      String(d.getDate()) + ' ' +
      String(d.getHours()) + ':' +
      String(d.getMinutes()) + ':' +
      String(d.getSeconds()); // yyyy-mm-dd-hh-mm-ss
    return time;
  },
})